const permissionConfig = require('../../config/config.permission');
const BaseService = require('../core/BaseService');

module.exports = class extends BaseService  {
  constructor(props) {
    super(props);
    this.tableName = 'user';
  }

  async info(id) {
    const { app, ctx } = this;
    id = id ? id : ctx.user.id;
    let user = await app.mysql.get(this.tableName, { id });
    if(!user){
      return ctx.fail('找不到该用户信息');
    }
    let userPermissions = null, menuPermissions = [], actionPermissions = [], permissionIds = [];
    if (!permissionConfig.whiteList.includes(String(user.authority))) {
      userPermissions = await app.mysql.select('user_permission', {
        where:{
          user_id: user.id
        }
      });
      for (let i = 0; i < userPermissions.length; i++) {
        let permission = await app.mysql.get('permission', {
          id: userPermissions[i].permission_id
        });
        userPermissions[i] = {...userPermissions[i], ...permission};
      }
    } else {
      userPermissions = await app.mysql.select('permission');
      for (let i = 0; i < userPermissions.length; i++) {
        userPermissions[i].permission_id = userPermissions[i].id;
      }
    }
    user.permissions = userPermissions;
    for (let i = 0; i < userPermissions.length; i++) {
      if (userPermissions[i] && userPermissions[i].type.includes('MENU')) {
        menuPermissions.push(userPermissions[i]);
      } else if (userPermissions[i] && userPermissions[i].type.includes('API')) {
        actionPermissions.push(userPermissions[i]);
      }
    }
    permissionIds = userPermissions.map(item => item.permission_id);
    user.menuPermissions = menuPermissions;
    user.actionPermissions = actionPermissions;
    user.permissionIds = permissionIds;
    return user;
  }

}